//
//  WHAttentionViewController.m
//  WHEasyBizLink
//
//  Created by ShengMeng on 9/19/25.

#import "WHFishSpotViewController.h"
#import "WHFishSpotTableViewCell.h"
#import "WHEnterpriseCompanyModel.h"
#import "WHFishSpotModel.h"
#import "WHFishSpotHeaderView.h"
#import "WHFishSpotSearchVC.h"
#import "UIBarButtonItem+XHBarButton.h"
#import "UIViewController+Sheet.h"
#import "WHFishSpotDetailVC.h"
#import "FilterPanelView.h"
#import "SearchTitleView.h"
#import "SDAutoLayout.h"
#import "WHTdsModel.h"
#import "MJRefresh.h"

#define pagesize 80

static NSString *const kCellID = @"WHEnterpriseCompanyCellID";

@interface WHFishSpotViewController ()<WHFishSpotHeaderViewDelegate,WHFishSpotHeaderViewDelegate,WHFishSpotTableViewCellDelegate>
@property(nonatomic,assign)CGFloat historyY;
@property (nonatomic,assign)int  mPageIndex;
@property(nonatomic,strong)NSString*searchString;
@property(nonatomic,strong)WHFishSpotHeaderView*headerView;
@property (nonatomic, strong) FilterPanelView *filterPanel;
@property (nonatomic, strong) UIControl *searchTitle;

@end

@implementation WHFishSpotViewController
- (void)viewDidLoad {
    self.mPageIndex = 1;
    self.searchString = @"";
    [super viewDidLoad];
    //self.view.backgroundColor =[UIColor whiteColor];
    self.navigationController.navigationBar.topItem.title = @"钓场";
  
}

#pragma mark - loadDatas
- (void)loadDatas{
    [super loadDatas];
    
    //[self getComListWithisdropDown:NO];
    
    self.datas =   [WHFishSpotModel getDatasModel:10];
    
}

#pragma mark - setupUI
- (void)setupUI{
    [super setupUI];
    //一个简单的super setupUI = createTableView
    
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonWithImage:[UIImage imageNamed:@"fishIcon"] highImage:[UIImage imageNamed:@"fishIcon"] type:UIBarButtonItemTypeRect target:self action:@selector(leftBarButtonItemClicked) forControlEvents:UIControlEventTouchUpInside];
    
    self.tableView.frame =CGRectMake(0,navHeight1,ScreenW,ScreenH-navHeight1);
    //self.navigationItem.rightBarButtonItem =self.rightItem;
    
    self.view.layer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"enterprise_bg"].CGImage);
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.subviews.firstObject.alpha = 0;
    
    self.tableView.backgroundColor =[UIColor clearColor];

    self.tableView.tableHeaderView = self.headerView;
    
    // Search titleView (tappable)
   
    self.navigationItem.titleView = self.searchTitle;
}

-(void)leftBarButtonItemClicked
{
    
}

#pragma mark 接收服务平台改变通知
-(void)notificationAction:(NSNotification *)notification{
    [self getComListWithisdropDown:NO];
}

#pragma mark - 查询公司列表
- (void)getComListWithisdropDown:(BOOL)isdropDown{
    NSDictionary *tds = [WHTdsModel getSelTDSProxyList];
    NSArray *allkey = [tds allKeys];
    if (allkey.count==0) {
        return;
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary new];
    dic[@"currPage"]     = [NSString stringWithFormat:@"%d",self.mPageIndex];//self.comModel.id;
    dic[@"perPageCount"] = [NSString stringWithFormat:@"%d",pagesize];
    dic[@"udid"]         = kApp.userPhone;
    dic[@"conditions"]   = self.searchString;
    dic[@"proxy"]        = tds[@"url"];
    dic[@"target"]       = tds[@"TDSid"];

    [WHEnterpriseCompanyModel  qryListCompanyWithFromdata:dic succesefulBlock:^(id  _Nonnull responseObject) {
        NSArray *dataList = (NSArray*)responseObject;
        
        if (dataList.count < pagesize){
            //拿到当前的小于Request_count时，表示没有更多的数据了
            [self setViewFooterWithHave:NO];
        }else{
            [self setViewFooterWithHave:YES];
            // 拿到当前的不小于Request_count时，表还有更多的数据了
            [self setViewFooterEndRefresh];
        }
        
        NSMutableArray *mutabelArray;
        if(isdropDown){
            [self.datas addObjectsFromArray:dataList];
            mutabelArray = self.datas;
        }else{
            mutabelArray = [NSMutableArray arrayWithArray:dataList];
        }
        self.datas =[NSMutableArray arrayWithArray:mutabelArray];
    } andFailureBlock:^(NSString * _Nonnull error) {
        
        self.datas = [NSMutableArray new];
    }];
}

#pragma mark 下拉刷新开始
- (void)dropDownRefresh
{
    if(!self.tableView.mj_footer) return;
    self.mPageIndex++;
    [self getComListWithisdropDown:YES];
}

- (void)setViewFooterWithHave:(BOOL) have{
    if(have){
        self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [self dropDownRefresh];
        }];
    }else{
        self.tableView.mj_footer =nil;
    }
}

- (void)setViewFooterEndRefresh{
    [self.tableView.mj_footer endRefreshing];
}



#pragma mark - <tableViewDelegate>
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    WHFishSpotTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:kCellID];
    if (!cell) {
        cell = [[WHFishSpotTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID];
    }
    cell.model = self.datas[indexPath.row];
    cell.delegate = self;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView
 heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 300;
    //return kMarginH*16;
}

-(void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
   
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    
    return NO;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WHFishSpotDetailVC *vc = [[WHFishSpotDetailVC alloc] initWithModel:self.datas[indexPath.row]];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];

}

-(void)wHFishSpotTableViewCellBtnClick:(UIButton *)btn
{
    if (btn.tag ==1) {
    [self  showActionSheet];
    }else if (btn.tag ==2)
    {
    }
}



-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

//设置滑动的判定范围
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if (self.historyY+20<targetContentOffset->y)
    {
        [self setTabBarHidden:YES];
    }
    else if(self.historyY-20>targetContentOffset->y)
    {
        [self setTabBarHidden:NO];
    }
    self.historyY=targetContentOffset->y;
}

#pragma mark 隐藏显示tabbar
- (void)setTabBarHidden:(BOOL)hidden
{
    UIView *tab = self.tabBarController.view;
    CGRect  tabRect=self.tabBarController.tabBar.frame;
    if ([tab.subviews count] < 2) {
        return;
    }

    UIView *view;
    if ([[tab.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]]) {
        view = [tab.subviews objectAtIndex:1];
    } else {
        view = [tab.subviews objectAtIndex:0];
    }

    if (hidden) {
        view.frame = tab.bounds;
        tabRect.origin.y=[[UIScreen mainScreen] bounds].size.height+self.tabBarController.tabBar.frame.size.height;
    } else {
        view.frame = CGRectMake(tab.bounds.origin.x, tab.bounds.origin.y, tab.bounds.size.width, tab.bounds.size.height);
        tabRect.origin.y=[[UIScreen mainScreen] bounds].size.height-self.tabBarController.tabBar.frame.size.height;
    }

    [UIView animateWithDuration:0.5f animations:^{
        self.tabBarController.tabBar.frame=tabRect;
    }completion:^(BOOL finished) {
    
    }];

}

-(void)wHFishSpotHeaderViewwBtnClick:(UIButton *)btn
{
    
    [self.filterPanel removeFromSuperview];
    
    NSArray*  options =@[];
    NSString*  title =@"";
    if (btn.tag ==1) {
        options = @[@"鲫鲤", @"鲫鱼", @"青鱼", @"草鱼",
                    @"翘嘴鱼", @"鳊鱼", @"罗非鱼", @"鳟鱼",
                    @"鲶鱼", @"鲤鱼", @"昂刺", @"混养",
                    @"鲢白鱼", @"白鲦", @"花鲢", @"黑鱼",
                     @"甲鱼", @"其他鱼", @"杂鱼（翘嘴、鳊鱼）"];
        title    = @"目标鱼种";
    }else if (btn.tag ==2)
    {
        options = @[@"随到随钓",@"定时定场"];
        title    = @"钓鱼钓法";
    }
    
    __weak typeof(self) weakSelf = self;
    self.filterPanel = [[FilterPanelView alloc] initWithHostViewController:self options:options title:title];
   
    self.filterPanel.selectionHandler = ^(NSArray<NSString *> * _Nonnull selectedOptions) {
            NSLog(@"Selected filters: %@", selectedOptions);
            // Use selectedOptions as needed
            [weakSelf.navigationItem.rightBarButtonItem setTitle:@"筛选"]; // keep title consistent
    };
  
    if (self.filterPanel.isVisible) {
        [self.filterPanel dismiss];
       
    } else {
        [self.filterPanel show];
    }
}
- (void)didTapSearchTitle {
    WHFishSpotSearchVC *vc = [[WHFishSpotSearchVC alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

-(WHFishSpotHeaderView *)headerView
{
    if (!_headerView)
    {
        _headerView=[[WHFishSpotHeaderView alloc]initWithFrame:CGRectMake(0, 0,ScreenW,220)];
        _headerView.delegate = self;
    }
    return  _headerView;
}
-(UIControl *)searchTitle
{
    if (!_searchTitle) {
        
        _searchTitle = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width - 140, 36)];
        _searchTitle.backgroundColor = [UIColor whiteColor];
        _searchTitle.layer.cornerRadius = 18.0;
        UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"magnifyingglass"]];
        icon.tintColor = [UIColor secondaryLabelColor];
        icon.frame = CGRectMake(10, 8, 20, 20);
        UILabel *placeholder = [[UILabel alloc] initWithFrame:CGRectMake(36, 0, _searchTitle.bounds.size.width - 46, 36)];
        placeholder.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        placeholder.text = @"搜索钓场";
        placeholder.textColor = [UIColor secondaryLabelColor];
        placeholder.font = [UIFont systemFontOfSize:15];
        [_searchTitle addSubview:icon];
        [_searchTitle addSubview:placeholder];
        [_searchTitle addTarget:self action:@selector(didTapSearchTitle) forControlEvents:UIControlEventTouchUpInside];
    }
    return _searchTitle;
}

@end

